package org.example.task.controller;


import jakarta.validation.Valid;
import jakarta.validation.constraints.NotNull;
import lombok.RequiredArgsConstructor;
import org.example.task.converter.RolePermissionConverterMapper;
import org.example.task.model.dto.PageDTO;
import org.example.task.model.dto.rolePermission.RolePermissionDTO;
import org.example.task.model.po.RolePermission;
import org.example.task.model.query.RolePermissionPageQuery;
import org.example.task.model.vo.R;
import org.example.task.model.vo.rolepermission.RolePermissionVO;
import org.example.task.service.IRolePermissionService;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;

/**
 * 角色权限管理接口
 *
 * @module 角色权限管理接口
 */
@RestController
@RequestMapping("/role-permission")
@RequiredArgsConstructor
@Validated
public class RolePermissionController {
    private final IRolePermissionService rolePermissionService;
    private final RolePermissionConverterMapper rolePermissionConverterMapper;

    /**
     * 查询角色权限列表
     *
     * @param rolePermissionPageQuery 请求数据
     * @return 结果
     */
    @GetMapping
    public R<PageDTO<RolePermissionVO>> getRolePermissionList(@Valid @RequestBody RolePermissionPageQuery rolePermissionPageQuery) {
        PageDTO<RolePermissionVO> result = rolePermissionService.getRolePermissionList(rolePermissionPageQuery);
        return R.success(result);
    }

    /**
     * 添加角色权限
     *
     * @param rolePermissionDTO 请求数据
     * @return 结果
     */
    @PostMapping
    public R addRolePermission(@Valid @RequestBody RolePermissionDTO rolePermissionDTO) {
        RolePermission rolePermission = rolePermissionConverterMapper.toRolePermission(rolePermissionDTO);
        rolePermission.setCreateTime(LocalDateTime.now());
        if (rolePermissionService.save(rolePermission)) {
            return R.success();
        }
        return R.error("操作失败");
    }

    /**
     * 删除角色权限
     *
     * @param roleId       角色id
     * @param permissionId 权限id
     * @return 结果
     */
    @DeleteMapping
    public R deleteRolePermissionById(@RequestParam @NotNull Long roleId, @RequestParam @NotNull Long permissionId) {
        if (rolePermissionService.removeRolePermissionById(roleId, permissionId)) {
            return R.success();
        }
        return R.error("操作失败");
    }
}
